package br.usp.icmc.biomac.client.view.impl;

import java.util.ArrayList; 
import java.util.List;

import br.usp.icmc.biomac.client.Resources.GlobalResources;
import br.usp.icmc.biomac.client.view.ImageAnnotation;
import br.usp.icmc.biomac.client.view.ImageView;
import br.usp.icmc.biomac.client.view.ROIImageCellTable;
import br.usp.icmc.biomac.shared.Arrow;
import br.usp.icmc.biomac.shared.Circle;
import br.usp.icmc.biomac.shared.Coordinate;
import br.usp.icmc.biomac.shared.ImageDicom;
import br.usp.icmc.biomac.shared.Line;
import br.usp.icmc.biomac.shared.OpenPoly;
import br.usp.icmc.biomac.shared.Oval;
import br.usp.icmc.biomac.shared.Poly;
import br.usp.icmc.biomac.shared.ROI;
import br.usp.icmc.biomac.shared.Rectangle;
import br.usp.icmc.biomac.shared.Comment;
import br.usp.icmc.biomac.client.activity.ImageListActivity;
import br.usp.icmc.biomac.shared.Slider;
import br.usp.icmc.biomac.shared.ROIShape;

import com.google.gwt.canvas.client.Canvas; 
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.CssColor;
import com.google.gwt.canvas.dom.client.FillStrokeStyle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.MouseWheelEvent;
import com.google.gwt.event.dom.client.MouseWheelHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label; 
import com.google.gwt.user.client.ui.Widget;

public class ImageViewImpl extends Composite implements ImageView {

	private static final Binder binder = GWT.create(Binder.class);

	public static final GlobalResources RESOURCE = GWT
			.create(GlobalResources.class);

	private Presenter presenter;
	private final Canvas canvas;
	private Context2d context;
	private final Canvas slider;
	private Context2d slidercont;
	private Image slideImg;

	private ImageAnnotation imageAnnotation;

	private final String elem = "canvas";
	private static final int drawHeight = 512;
	private static final int drawWidth = 512;
	private static final int slideHeight = 35;
	private boolean click,clicado, mouseDown, imageLoad, mouseDownSlider = false;
	
	// control drawing
	private Tool tool;
	private ROIShape drawShape = null;
	private boolean drawMode = false;
	private Drawing drawing;

	//private List<Coordinate> coords  = new ArrayList<Coordinate>(); 
	private int atualX, atualY, imageIndex = 0;
	private int mouseX, mouseY;
	private final FillStrokeStyle strokeStyle = CssColor.make("#32CD32");// #333300

	enum Tool {gradientTool, moveTool, zoomTool, rotateTool, animateTool, drawTool};
	
	
	private ImageElement arrowSlideImage;
	private final Image logoImg = new Image("slider.png");
	private final FillStrokeStyle strokeStyleSlider = CssColor.make("#909090");// #333300
	private final FillStrokeStyle strokeStyleSliderArrow = CssColor.make("#FFFFFF");// #333300

	
	ROIImageCellTable roiTable;

	@UiField
	HTMLPanel canvasArea;
	@UiField
	HTMLPanel drawArea;
	@UiField
	Label imageWC;
	@UiField
	Label imageWW;
	@UiField
	Label imageY;
	@UiField
	Label imageX;
	@UiField
	Label totalImage;
	@UiField
	Label levelImage;
	@UiField
	AbsolutePanel AbPanel;
	@UiField
	HTMLPanel slidePanel;
	@UiField 
	HTMLPanel svgArea; 

	/*
	@UiField
	Button b_add;
	@UiField
	Button b_rmv;
	@UiField
	Button c_add;
	@UiField
	Button c_rmv;
	@UiField
	Button downImages;
	@UiField
	Button upImages;
	@UiField
	Button resetImages;
	@UiField
	Button selectImage;
	@UiField
	ToggleButton drawLine;
	*/
	@UiField
	HTMLPanel slidePanelOld;
	/*
	@UiField
	ToggleButton drawRectangle;
	*/
	@UiField
	FlexTable rowList;
	/*
	@UiField
	Button annotationTool;
	*/
	@UiField
	Button level;
	@UiField
	Button move;
	@UiField
	Button zoom;
	@UiField
	Button animate;
	@UiField
	Button rotate;
	@UiField
	Button draw;
	@UiField
	Button tile;
	@UiField
	Button settings;
	@UiField
	Button help;
	@UiField
	Button delete;
	@UiField
	Button annotate;
	
	//@UiField
	//TextBox slide;
	//@UiField
	//TextBox count;
	@UiField
	Button line;
	@UiField
	Button rectangle;
	@UiField
	Button circle;
	@UiField
	Button poly;
	@UiField
	Button openPoly;
	@UiField
	Button oval;
	//@UiField
	//Button text;
	@UiField
	Button arrow;
	@UiField
	Button one;
	@UiField
	Button two;
	@UiField
	Button four;
	@UiField
	Button table;
	@UiField
	Button browser;
	@UiField
	Button tab;
	@UiField
	Button reset;
	@UiField
	Button abdomen;
	@UiField
	Button bone;
	@UiField
	Button brain;
	@UiField
	Button pulmonary;
	@UiField
	Button endoscopy;
	
	@UiField
	  Slider imageSlider;
	
	
	

	interface Binder extends UiBinder<Widget, ImageViewImpl> {
	}
	
	public ImageViewImpl() {
		initWidget(binder.createAndBindUi(this));
		initToolBar();
		initImageSlider(0);
		drawing = new Drawing( drawWidth,drawHeight, drawWidth,drawHeight, 10, 0);
		svgArea.add(drawing);
				
		// set tab active
				//drawLine.setDown(false);
				canvas = Canvas.createIfSupported();
				slider = Canvas.createIfSupported();
				
				
				// upImages.add
				if (canvas != null) {
					canvas.setWidth(drawWidth + "px");
					canvas.setHeight(drawHeight + "px");
					canvas.setCoordinateSpaceWidth(drawWidth);
					canvas.setCoordinateSpaceHeight(drawHeight);
				} else
					drawArea.add(new Label(
							"Your browser does not support the HTML5 Canvas. Please upgrade your browser to view this App."));
				if (slider != null) {
					slider.setWidth(drawWidth + "px");
					slider.setHeight(slideHeight + "px");
					slider.setCoordinateSpaceWidth(drawWidth);
					slider.setCoordinateSpaceHeight(slideHeight);
					slidePanel.add(slider);
				} else
					drawArea.add(new Label(
							"Your browser does not support the HTML5 Canvas. Please upgrade your browser to view this App."));
					
				//drawArea.add(canvas);  // just for now
				context = canvas.getContext2d();
				slidercont = slider.getContext2d();
				//initHandlers();  // just for now
				initDrawingHandlers();
				initHandlersSlider();
				//drawImage();
				
				
				
	}

	public ImageViewImpl(ROIImageCellTable roiTable) {
		this();
		this.roiTable = roiTable;
	}

	@Override
	public Widget asWidget() {
		return this;
	}
	
	public ImageViewImpl(ROIImageCellTable roiTable, ImageAnnotation imageAnnotation) {
		this(roiTable);
		this.imageAnnotation = imageAnnotation;
	}

	public ImageViewImpl(ROIImageCellTable roiTable,
			ImageAnnotation imageAnnotation, String series) {
		this(roiTable, imageAnnotation);

	}

	@Override
	public void setData(List<ImageDicom> Images) {
		
		// reset the drawing
		drawing.reset(Images.size());
		
		for (int i = 0; i < Images.size(); ++i) {
			addImage(Images.get(i).getUrl(), elem);
			Images.get(i).setId(Integer.toString(i));
			//presenter.setIndexImage(0);
			// create the drawing layer from the roi list
			buildROI(i);
		}
		presenter.setIndexImage(0);
		presenter.setImages((ArrayList<ImageDicom>) Images);
		imageLoad = true;
		totalImage.setText(Integer.toString(Images.size()));
		levelImage.setText(Integer.toString(getIndexImage() + 1));
		drawSliderArrow();
		initImageSlider(Images.size()); 
		
	}
	

	
	// create the new ROI from the current drawing shape
	private void newROI() {
		
		Coordinate from = new Coordinate(atualX, atualY);
		Coordinate to = new Coordinate(mouseX, mouseY);
		List<Coordinate> coords  = drawing.getCoordsShape();
		String title = "ROI " + Integer.toString(getNumberROIs()+1);
		
		switch (drawShape) {
		
		case LINE:
			presenter.addROI(getIndexImage(), new Line(title, from, to)); 
			break;
		
		case RECTANGLE:
			presenter.addROI(getIndexImage(), new Rectangle(title, from, to));
			break;
		
		case CIRCLE:
			presenter.addROI(getIndexImage(), new Circle(title, from, to));
			break;
		
		case OVAL:
			presenter.addROI(getIndexImage(), new Oval(title, from, to));
			break;
		
		case POLY:
			presenter.addROI(getIndexImage(), new Poly(title, coords));
			break;
		
		case OPENPOLY:
			presenter.addROI(getIndexImage(), new OpenPoly(title, coords));
			break;
			
		case ARROW:
			presenter.addROI(getIndexImage(), new Arrow(title, from, to));
			break;
		}

		drawImage();
	}
	

	
	// build the drawing shape set from the ROI list for the image
	private void buildROI(int set) {
		
			List<ROI> roi = presenter.getImages().get(set).getRois();
			for (int a = 0; a < roi.size(); ++a) {
				if (roi.get(a) instanceof Line) {
					Line line = (Line) roi.get(a);
					drawing.buildShape(set, ROIShape.LINE, line.getCoordinates());
				}
				if (roi.get(a) instanceof Rectangle) {
					Rectangle rect = (Rectangle) roi.get(a);
					drawing.buildShape(set, ROIShape.RECTANGLE, rect.getCoordinates());
				}
				
				if (roi.get(a) instanceof Circle) {
					Circle circle = (Circle) roi.get(a);
					drawing.buildShape(set, ROIShape.CIRCLE, circle.getCoordinates());
				}
				
				if (roi.get(a) instanceof Oval) { 
					Oval oval = (Oval) roi.get(a);
					drawing.buildShape(set, ROIShape.OVAL, oval.getCoordinates());
				}
				
				if (roi.get(a) instanceof Poly) {
					Poly poly = (Poly) roi.get(a);
					drawing.buildShape(set, ROIShape.POLY, poly.getCoordinates());
				}
				
				if (roi.get(a) instanceof OpenPoly) { 
					OpenPoly openPoly = (OpenPoly) roi.get(a);
					drawing.buildShape(set, ROIShape.OPENPOLY, openPoly.getCoordinates());
				}
				
				if (roi.get(a) instanceof Arrow) {
					Arrow arrow = (Arrow) roi.get(a);
					drawing.buildShape(set, ROIShape.ARROW, arrow.getCoordinates());
				}

			}
			table_ROIS();
			
	}

	

	@Override
	public void drawImage() {
	
		console("drawImage ");
		levelImage.setText(Integer.toString(getIndexImage() + 1));
		/*
		context.setStrokeStyle(strokeStyle);
		context.clearRect(-1, -1, 512, 512);
		// print ROI
		List<ROI> roi = presenter.getImages().get(getIndexImage()).getRois();
		for (int a = 0; a < roi.size(); ++a) {
			if (roi.get(a) instanceof Line) {
				Line line = (Line) roi.get(a);
				drawing.addLine(line.getCood1().getX(), line.getCood1().getY(), line.getCood2().getX(),line.getCood2().getY());
			}
			if (roi.get(a) instanceof Rectangle) {
				Rectangle rect = (Rectangle) roi.get(a);
				drawing.addRectangle(rect.getCood1().getX(), rect.getCood1().getY(), rect.getCood2().getX(),rect.getCood2().getY());
			}
			
			if (roi.get(a) instanceof Circle) {
				Circle circle = (Circle) roi.get(a);
				drawing.addCircle(circle.getCood1().getX(), circle.getCood1().getY(), circle.getCood2().getX(),circle.getCood2().getY());
			}
			
			if (roi.get(a) instanceof Arrow) {
				Arrow arrow = (Arrow) roi.get(a);
				drawing.addArrow(arrow.getCood1().getX(), arrow.getCood1().getY(), arrow.getCood2().getX(), arrow.getCood2().getY());
			}
			
			if (roi.get(a) instanceof Comment) {
				Comment comment = (Comment) roi.get(a);
				drawing.addText(comment.getCood1().getX(), comment.getCood1().getY(), roi.get(a).getLabel());  
			}
			
			if (roi.get(a) instanceof Poly) {
				Poly poly = (Poly) roi.get(a);
				drawing.addPoly(poly.getCoordinates());
			}
			if (roi.get(a) instanceof OpenPoly) { 
				OpenPoly openPoly = (OpenPoly) roi.get(a);
				drawing.addOpenPoly(openPoly.getCoordinates());
			}
			if (roi.get(a) instanceof Oval) { 
				Oval oval = (Oval) roi.get(a);
				drawing.addEllipse(oval.getCood1().getX(), oval.getCood1().getY(), oval.getCood2().getX(),oval.getCood2().getY());
			}
			

		}*/
		table_ROIS();
	}

	public void table_ROIS() {
		roiTable.setDataResult(presenter.getImages().get(getIndexImage()).getRois());
		slidePanelOld.clear();
		slidePanelOld.add(roiTable);
	} 
	
	// draw an arrow ROI
	private void drawArrow(int fromx, int fromy, int tox, int toy){
		/*
	    int headlen = 10;   // length of head in pixels
	    double angle = Math.atan2(toy-fromy,tox-fromx);
	    context.setStrokeStyle(strokeStyle);
	    context.beginPath();
	    context.moveTo(fromx, fromy);
	    context.lineTo(tox, toy);
	    context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
	    context.moveTo(tox, toy);
	    context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
	    context.closePath();
		context.stroke();
		*/ 
	}
	
	// draw a line ROI
	private void drawLine(int fromX, int fromY, int toX, int toY){
		/*
		console("drawLine");
		context.setStrokeStyle(strokeStyle);
		context.beginPath();
		context.lineTo(fromX, fromY);
		context.lineTo(toX, toY);
		context.closePath();
		context.stroke(); 
		*/
	}
	
	// draw a line ROI
	private void drawRectangle(int fromX, int fromY, int toX, int toY){
		/*
		console("drawRectangle");
		context.setStrokeStyle(strokeStyle);
		context.beginPath();
		context.rect(fromX, fromY, toX, toY);
		context.closePath();
		context.stroke();
		*/
	}
	
	// draw a circle ROI
	private void drawCircle(int fromX, int fromY, int toX, int toY){
		/*
		console("drawCircle");
		context.setStrokeStyle(strokeStyle);
		context.beginPath();
		context.arc(toX - (toX - fromX)/2, toY - (toY - fromY)/2,(toX - fromX + toY - fromY)/Math.PI,0,Math.PI*2,true);
		context.closePath();
		context.stroke();
		*/
	}

	// draw an oval ROI
	private void drawOval(int fromX, int fromY, int toX, int toY){
		/*
		console("drawOval");
		context.setStrokeStyle(strokeStyle);	
		context.beginPath();
		int centerX = fromX + (toX - fromX)/2;
		int centerY = fromY + (toY - fromY)/2;
		int height = (toY - fromY);
		int width = (toX - fromX);
			  
		context.moveTo(centerX, centerY - height/2); // A1
			  
		context.bezierCurveTo(
			    centerX + width/2, centerY - height/2, // C1
			    centerX + width/2, centerY + height/2, // C2
			    centerX, centerY + height/2); // A2

		context.bezierCurveTo(
			    centerX - width/2, centerY + height/2, // C3
			    centerX - width/2, centerY - height/2, // C4
			    centerX, centerY - height/2); // A1
			 

		context.stroke();
		context.closePath();
		*/	
	
	}
	 // draw a text comment
	private void drawComment(String label, int fromX, int fromY){
		/*
		console("drawComment");
		context.setStrokeStyle(strokeStyle);
		context.strokeText(label, fromX, fromY);
		*/
	}
	
	// draw a polygon with the coordinate list
	private void drawPoly(List<Coordinate> coord) {
		/*
		if (coord.size() > 0) {
			context.setStrokeStyle(strokeStyle);	
			context.beginPath(); 
			context.moveTo(coord.get(0).getX(), coord.get(0).getY());   
			for (int i = 1; i < coord.size(); i++) {  
				context.lineTo(coord.get(i).getX(), coord.get(i).getY());
				}
			context.stroke();
			context.closePath();
		}
		*/
	}
	
	// draw the poly with the move point tacked on as the last line
	private void ghostPoly(List<Coordinate> coord, int x, int y) {
		/*
		if (coord.size() > 0) {
			context.setStrokeStyle(strokeStyle);	
			context.beginPath(); 
			context.moveTo(coord.get(0).getX(), coord.get(0).getY());   
			for (int i = 1; i < coord.size(); i++) {  
				context.lineTo(coord.get(i).getX(), coord.get(i).getY());
				}
			context.lineTo(x, y);
			context.stroke();
			context.closePath();
		}
		*/
	}
	
	
	/*
	
	// start drawing a shape
	private void startShape(Shape shape) {

		clicado = true;
		if (!drawMode) {
			drawMode = true;
			coords = new ArrayList<Coordinate>();
		}
	}
	
	// test for the end of drawing a poly
	private boolean stopShape (Coordinate c) {
		// TODO Auto-generated method stub
		boolean stop = false;
		
		if (drawMode && coords.size() > 1) {
			
			if (drawShape == Shape.polyShape) {
				int deltaX = Math.abs(coords.get(0).getX() - c.getX());
				int deltaY = Math.abs(coords.get(0).getY() - c.getY());
				stop =  (deltaX < 10) && (deltaY < 10);
				
			}
			if (drawShape == Shape.openPolyShape) {
				int last = coords.size() - 2;
				int deltaX = Math.abs(coords.get(last).getX() - c.getX());
				int deltaY = Math.abs(coords.get(last).getY() - c.getY());
				stop =  (deltaX < 10) && (deltaY < 10);
			
			}
		
		
			if (stop) {
				drawMode = false;
			}
		}
		return stop;
	}
	
	// close the poly shape automatically
	private void closeShape (Coordinate c) {		
		
		if ((coords.size() > 1) && (drawShape == Shape.polyShape)) {
			int last = coords.size() - 1;
			int x = coords.get(0).getX();
			int y = coords.get(0).getY();
			coords.get(last).setX(x);
			coords.get(last).setY(y);
		}
		
	}
	
	*/
	
	/*
	void initHandlers() {
		
		
		canvas.addMouseMoveHandler(new MouseMoveHandler() {
			@Override
			public void onMouseMove(MouseMoveEvent event) {
				mouseX = event.getRelativeX(canvas.getElement());
				mouseY = event.getRelativeY(canvas.getElement());
				imageX.setText(Integer.toString(mouseX));
				imageY.setText(Integer.toString(mouseY));
				
				switch (tool) {
				// change the coordinates numbers and change the brightness of
				// image
				case gradientTool:
					if (imageLoad) {
						try {
							handleImageMouseMove(Integer.toString(mouseX),
									Integer.toString(mouseY));
							imageWC.setText(Integer.toString(wcImage()));
							imageWW.setText(Integer.toString(wwImage()));
						} catch (Exception e) {
							GWT.log("JSNI methodo handleImage() threw a exception: ",
									e);
							e.printStackTrace();
						}
					}
					break;
				// change the new line 
				case drawTool: if  (clicado == true)  {
						switch (drawShape) {
						case lineShape:  
							drawImage();
							drawLine(atualX, atualY, mouseX, mouseY);
							break;
						case rectangleShape: 
							drawImage();
							drawRectangle(atualX, atualY, mouseX - atualX, mouseY - atualY);
							break;
						case circleShape:
							drawImage();
							drawCircle(atualX, atualY, mouseX, mouseY);
							break;
						case polyShape:
							drawImage();
							ghostPoly(coords, mouseX, mouseY);
							break;
						case openPolyShape:
							drawImage();
							ghostPoly(coords, mouseX, mouseY);
							break;
						case ovalShape:
							drawImage();
							drawOval(atualX, atualY, mouseX, mouseY);
							break;
						case textShape:break;
						case arrowShape:
							drawImage();
							drawArrow(atualX, atualY, mouseX, mouseY);
							break;
		
						}
						break;
					}
				}
			}
		});
		
		canvas.addMouseDownHandler(new MouseDownHandler() {// 1
			@Override
			public void onMouseDown(MouseDownEvent event) {
				atualX = mouseX;
				atualY = mouseY;
				switch (tool) {
				case gradientTool:
					if (imageLoad) {
						handleImageMouseDown(Integer.toString(mouseX),
								Integer.toString(mouseY));
					}
					break;
				case moveTool: break;
				case zoomTool:break;
				case animateTool: break;
				case rotateTool: break;
				case drawTool:

					startShape(drawShape);
					break;
				}
	
			}

			
		});
		
		canvas.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				switch (tool) {
				case drawTool:
					if (clicado == true) {
						switch (drawShape) {
						
						case textShape:
							context.setStrokeStyle(strokeStyle);
							context.clearRect(-1, -1, 512, 512);
							context.beginPath();

							String s = Character.toString(event.getCharCode());

							drawComment(s,  atualX, atualY);
							context.closePath();
							context.stroke();
							break;
		
						}
					}
					break;
				}
			}
		});
		
		canvas.addMouseUpHandler(new MouseUpHandler() {// 3
			@Override
			public void onMouseUp(MouseUpEvent event) {
				switch (tool) {
				case gradientTool:
					if (imageLoad) {
						handleImageMouseUp();
					}
					break;
				case drawTool:
					if (clicado == true) {
						switch (drawShape) {
						case lineShape:
							clicado = false;
							drawLine(atualX, atualY, mouseX, mouseY);
							presenter.addROI(getIndexImage(),
									new Line("ROI " + Integer.toString(getNumberROIs()+1),
											new Coordinate(atualX, atualY),
											new Coordinate(mouseX, mouseY)));
							drawImage();
							break;
						case rectangleShape:
							clicado = false;
							drawRectangle(atualX, atualY, mouseX, mouseY);
							presenter.addROI(getIndexImage(),
									new Rectangle("ROI " + Integer.toString(getNumberROIs()+1),
											new Coordinate(atualX, atualY),
											new Coordinate(mouseX - atualX, mouseY - atualY)));
							drawImage();
							break;
						case polyShape:
							Coordinate c = new Coordinate(mouseX,mouseY);
							coords.add(c);
							if (stopShape(c)) {
								closeShape(c);
								drawPoly(coords);
								
								clicado = false;
							
								presenter.addROI(getIndexImage(),
										new Poly("ROI " + Integer.toString(getNumberROIs()+1), coords));
								drawImage();
							} else {
								
								drawPoly(coords);
							}
							
							break;
						case openPolyShape:
							Coordinate o = new Coordinate(mouseX,mouseY);
							coords.add(o);
							if (stopShape(o)) {
								
								drawPoly(coords);
								clicado = false;
								
								presenter.addROI(getIndexImage(),
										new OpenPoly("ROI " + Integer.toString(getNumberROIs()+1), coords));
								drawImage();
							} else {	
								drawPoly(coords);
							}
							break;
						case circleShape:
							clicado = false;
							drawCircle(atualX, atualY, mouseX, mouseY);
							presenter.addROI(getIndexImage(),
									new Circle("ROI " + Integer.toString(getNumberROIs()+1),
											new Coordinate(atualX, atualY),
											new Coordinate(mouseX, mouseY)));
							drawImage();
							break;
						case ovalShape:
							clicado = false;
							drawOval(atualX, atualY, mouseX, mouseY);
							presenter.addROI(getIndexImage(),
									new Oval("ROI " + Integer.toString(getNumberROIs()+1),
											new Coordinate(atualX, atualY),
											new Coordinate(mouseX, mouseY)));
							drawImage();
							break;
						case arrowShape:
							clicado = false;
							drawArrow(atualX, atualY, mouseX, mouseY);
							presenter.addROI(getIndexImage(),
									new Arrow("ROI " + Integer.toString(getNumberROIs()+1),
											new Coordinate(atualX, atualY),
											new Coordinate(mouseX, mouseY)));
							drawImage();
							break;
						case textShape:
							context.setStrokeStyle(strokeStyle);
							context.beginPath();
							drawComment("ROI " + Integer.toString(getNumberROIs()+1), atualX, atualY);
							context.closePath();
							context.stroke();
				
							clicado = false;
							presenter.addROI(getIndexImage(),
									new Comment("ROI " + Integer.toString(getNumberROIs()+1), 
											new Coordinate(atualX, atualY),
											new Coordinate(mouseX, mouseY)));
							drawImage();
							break;
						}
			
				
					}
				
					break;
				}
			}

			
			
		});
		
		canvas.addMouseWheelHandler(new MouseWheelHandler() {
			@Override
			public void onMouseWheel(MouseWheelEvent event) {
				if (imageLoad) {
					if (event.getDeltaY() < 0) {
						upImages();
						if ((presenter.getImages().size() - 1) > getIndexImage())
							setIndexImage(getIndexImage() +1);
					} else {
						downImages();
						if (0 < getIndexImage())
							setIndexImage(getIndexImage() -1);
					}
					drawImage();
					drawSliderArrow();
					updateSlider();
			
				}
			}
		});
	}
	*/

	void initHandlersSlider() {
		slider.addMouseMoveHandler(new MouseMoveHandler() {
			@Override
			public void onMouseMove(MouseMoveEvent event) {
				mouseX = event.getRelativeX(slider.getElement());
				mouseY = event.getRelativeY(slider.getElement());
				if (mouseDownSlider) {
					setIndexImage(mouseX / (drawWidth / presenter.getImages().size()));
					if (getIndexImage() > presenter.getImages().size())
						setIndexImage(presenter.getImages().size());
					drawSliderArrow();
				}

			}
		});

		slider.addMouseDownHandler(new MouseDownHandler() {// 1
			@Override
			public void onMouseDown(MouseDownEvent event) {
				setIndexImage(mouseX / (drawWidth / presenter.getImages().size()));
				if (getIndexImage() > presenter.getImages().size())
					setIndexImage(presenter.getImages().size());
				drawSliderArrow();
				mouseDownSlider = true;
				slider.setFocus(false);
			}
		});
		slider.addMouseUpHandler(new MouseUpHandler() {// 3
			@Override
			public void onMouseUp(MouseUpEvent event) {
				mouseDownSlider = false;
				slider.setFocus(false);
			}
		});
	}

	public void drawSliderArrow() {
		
		if (!imageLoad)
			return;
		arrowSlideImage = (ImageElement) logoImg.getElement().cast();
		double elemento = getIndexImage()
				* ((drawWidth / presenter.getImages().size()));
		elemento += (drawWidth / presenter.getImages().size() / 2);
		// clean context 2d
		slidercont.setStrokeStyle(strokeStyleSlider);
		slidercont.clearRect(-1, -1, 512, 50);
		// draw a grade elements
		for (int i = 0; i < presenter.getImages().size(); ++i) {
			slidercont.beginPath();
			int x = ((drawWidth / presenter.getImages().size()) * (i))
					+ (drawWidth / presenter.getImages().size() / 2);
			slidercont.lineTo(x, 0);
			slidercont.lineTo(x, 15);
			slidercont.closePath();
			slidercont.stroke();
		}
		slidercont.setStrokeStyle(strokeStyleSliderArrow);
		slidercont.beginPath();
		slidercont.lineTo((int) elemento, 0);
		slidercont.lineTo((int) elemento, 15);
		slidercont.closePath();
		slidercont.stroke();
		slidercont.drawImage(arrowSlideImage, (int) elemento - 5, 15);
		changeLevelImage(getIndexImage());
		drawImage();
		slider.setFocus(false);
		
	}
	
	
	
	
/*
	@UiHandler("upImages")
	void onUpImagesClick(ClickEvent event) {
		upImages();
		if ((presenter.getImages().size() - 1) > getIndexImage())
			setIndexImage(getIndexImage()+1);
		drawImage();
	}

	@UiHandler("downImages")
	void onDownImagesClick(ClickEvent event) {
		downImages();
		if (0 < imageIndex)
			--imageIndex;
		drawImage();
	}

	@UiHandler("b_add")
	void onB_addClick(ClickEvent event) {
		b_add();
	}

	@UiHandler("b_rmv")
	void onB_rmvClick(ClickEvent event) {
		b_rmv();
	}

	@UiHandler("c_add")
	void onC_addClick(ClickEvent event) {
		c_add();
	}

	@UiHandler("c_rmv")
	void onC_rmvClick(ClickEvent event) {
		c_rmv();
	}

	@UiHandler("resetImages")
	void onResetImagesClick(ClickEvent event) {
		resetImages();
	}
*/
	public native String loadImages()/*-{
		$wnd.startImage();
	}-*/;

	public native String upImages()/*-{
		$wnd.moveCamada(1);
	}-*/;

	public native String downImages()/*-{
		$wnd.moveCamada(-1);
	}-*/;
	
	public native String moveImages(int val)/*-{
	    $wnd.moveCamada(val);
    }-*/;

	public native String b_add()/*-{
		$wnd.applyBrilho(-1);
	}-*/;

	public native String b_rmv()/*-{
		$wnd.applyBrilho(1);
	}-*/;

	public native String c_add()/*-{
		$wnd.applycontraste(1);
	}-*/;

	public native String c_rmv()/*-{
		$wnd.applycontraste(-1);
	}-*/;

	public native String resetImages()/*-{
		$wnd.reset(-1);
	}-*/;

	public native String handleImageMouseMove(String x, String y)/*-{
		$wnd.mousemoveHandler2(x, y);
	}-*/;

	public native String handleImageMouseUp()/*-{
		$wnd.mouseupHandler2();
	}-*/;

	public native String handleImageMouseDown(String x, String y)/*-{
		$wnd.mouseDownHandler2(x, y);
	}-*/;

	public void addImage(String url, String elem) {
		addImage2(
				GWT.getModuleBaseURL() + "dcmstream?wadourl="
						+ url.replaceAll("&", "-"), elem);
	}

	public native String addImage2(String url, String elem)/*-{
		$wnd.addImage(url, elem);
	}-*/;

	public native int wcImage()/*-{

		return $wnd.WebPad_wc;
	}-*/;

	public native int wwImage()/*-{
		return $wnd.WebPad_ww;
	}-*/;

	public native String changeLevelImage(int id)/*-{
		$wnd.changeLevelImage(id);
	}-*/;
	
	private static native void console(String message) /*-{
	    //console.clear();
	    console.log(message);
	}-*/;

/*
	@UiHandler("selectImage")
	void onSelectImageClick(ClickEvent event) {
		tool = 0;
		selectImage.setFocus(false);
		drawLine.setDown(false);
		drawRectangle.setDown(false);
	}
*/
	@UiHandler("line")
	void onDrawLineClick(ClickEvent event) {

		toggleDrawMode(line, ROIShape.LINE);
	}

	@UiHandler("rectangle")
	void onDrawRectangleClick(ClickEvent event) {
		
		toggleDrawMode(rectangle, ROIShape.RECTANGLE);
	}

	@UiHandler("circle")
	void onDrawCircleClick(ClickEvent event) {

		toggleDrawMode(circle, ROIShape.CIRCLE);
	}
	
	@UiHandler("poly")
	void onDrawPolyClick(ClickEvent event) {

		toggleDrawMode(poly, ROIShape.POLY);
	}
	
	@UiHandler("openPoly")
	void onDrawOpenPolyClick(ClickEvent event) {
		
		toggleDrawMode(openPoly, ROIShape.OPENPOLY);
	}
	
	@UiHandler("oval")
	void onDrawOvalClick(ClickEvent event) {
		
		toggleDrawMode(oval, ROIShape.OVAL);
	}
	/*
	@UiHandler("text")
	void onDrawTextClick(ClickEvent event) {
		
		selectDrawMode(text, Shape.textShape, "text");
	}
	*/
	
	@UiHandler("arrow")
	void onDrawArrowClick(ClickEvent event) {
		
		toggleDrawMode(arrow, ROIShape.ARROW);
	}
	
	@UiHandler("delete")
	void onDeleteClick(ClickEvent event) {
		
		drawing.deleteShape();
	}
	

	
	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
		imageAnnotation.setPresenter((br.usp.icmc.biomac.client.view.ImageAnnotation.Presenter) presenter);
		roiTable.setPresenter((br.usp.icmc.biomac.client.view.ROIImageCellTable.Presenter) presenter);
	}

	@UiHandler("annotate")
	void onAnnotateClick(ClickEvent event) {
		imageAnnotation.showAnnotation();
		imageAnnotation.updateTemplatesContainers();
	}
	/*
	private Button getSelected() {
		return level;	
	}
	*/
	
	
	@UiHandler("level")
	void onClickLevel(ClickEvent e) {
		// remove the selected mode
		toggleMode(level, "edit-level");
		
	}
	
	@UiHandler("move")
	void onClickMove(ClickEvent e) {
		// set up move mode
		toggleMode(move, "edit-move");
	}
	
	@UiHandler("zoom")
	void onClickZoom(ClickEvent e) {
		// set up zoom mode
		toggleMode(zoom, "edit-zoom");
	}
	
	@UiHandler("animate")
	void onClickAnimate(ClickEvent e) {
		// set up animate mode
		toggleMode(animate, "edit-animate");
	}
	
	@UiHandler("rotate")
	void onClickRotate(ClickEvent e) {
		// set up zoom mode
		toggleMode(rotate, "edit-rotate");
	}
	
	@UiHandler("tile")
	void onClickTile(ClickEvent e) {
		// set up zoom mode
		toggleMode(tile, "edit-tile");
	}

	@UiHandler("one")
	void onClickTileOne(ClickEvent e) {
		// set up zoom mode
		selectTileMode(one);
	}
	
	// handle a click on two page tiling button
	@UiHandler("two")
	void onClickTileTwo(ClickEvent e) {
		// set up zoom mode
		selectTileMode(two);
	}
	
	// handle a click on four page tiling button
	@UiHandler("four")
	void onClickTileFour(ClickEvent e) {
		// set up zoom mode
		selectTileMode(four);
	}
	
	// handle a click on the settings button
	@UiHandler("settings")
	void onClickSettings(ClickEvent e) {
		// set up settings mode
		toggleMode(settings, "edit-settings");
	}
	
	// handle a click on table button in settings drawer
	@UiHandler("table")
	void onClickSettingsTable(ClickEvent e) {
		// set up zoom mode
		selectSettingsMode(table);
	}
	
	// handle a click on the browser button in settings drawer
	@UiHandler("browser")
	void onClickSettingsBrowser(ClickEvent e) {
		// set up zoom mode
		selectSettingsMode(browser);
	}
	
	
	// handle a click on the draw button
	@UiHandler("draw")
	void onClickDraw(ClickEvent e) {
		// set up draw mode
		toggleMode(draw, "edit-draw");
	}
	
	// handle a click on the reset button
	@UiHandler("reset")
	void onResetClick(ClickEvent event) {
		resetImages();
	}
	
	public int getNumberROIs(){
		return presenter.getImages().get(getIndexImage()).getRois().size();
	}
	
	public int getIndexImage(){
		return presenter.getIndexImage();
	}
	
	public void setIndexImage(int index){
		presenter.setIndexImage(index);
	}
	

	
	
	// initialized the toolbar and drawer classes and ids 
	private void initToolBar(){
		
		// add the button class and id
		level.getElement().addClassName("btn");
		level.getElement().setId("edit-gradient");
		move.getElement().addClassName("btn");
		move.getElement().setId("edit-move-shift");
		zoom.getElement().addClassName("btn");
		zoom.getElement().setId("edit-zoom");
		rotate.getElement().addClassName("btn");
		rotate.getElement().setId("edit-rotate-right");
		animate.getElement().addClassName("btn");
		animate.getElement().setId("edit-animate");
		tile.getElement().addClassName("btn");
		tile.getElement().setId("edit-tile");
		draw.getElement().addClassName("btn");
		draw.getElement().setId("edit-draw");
		annotate.getElement().addClassName("btn");
		annotate.getElement().setId("edit-annotate");
		settings.getElement().addClassName("btn");
		settings.getElement().setId("edit-settings");
		help.getElement().addClassName("btn");
		help.getElement().setId("edit-help");
		tab.getElement().addClassName("btn");
		tab.getElement().setId("edit-tab");
		
		// not using the trash can right now
		delete.getElement().addClassName("btn");  
		delete.getElement().setId("edit-delete");
		
		// buttons for drawing drawer
		line.getElement().addClassName("btn");
		line.getElement().setId("draw-line");
		rectangle.getElement().addClassName("btn");
		rectangle.getElement().setId("draw-rectangle");
		circle.getElement().addClassName("btn");
		circle.getElement().setId("draw-circle");
		oval.getElement().addClassName("btn");
		oval.getElement().setId("draw-oval");
		poly.getElement().addClassName("btn");
		poly.getElement().setId("draw-poly");
		openPoly.getElement().addClassName("btn");
		openPoly.getElement().setId("draw-openpoly");
		//text.getElement().addClassName("btn");
		//text.getElement().setId("draw-text");
		arrow.getElement().addClassName("btn");
		arrow.getElement().setId("draw-arrow");
		
		// buttons for settings drawer
		table.getElement().addClassName("btn");
		table.getElement().setId("settings-table");
		browser.getElement().addClassName("btn");
		browser.getElement().setId("settings-browser");
		
		// set up tiling drawer
		one.getElement().addClassName("btn");
		one.getElement().setId("tile-one-page");
		two.getElement().addClassName("btn");
		two.getElement().setId("tile-two-pages");
		four.getElement().addClassName("btn");
		four.getElement().setId("tile-four-pages");
		
		// set up leveling drawer
		reset.getElement().addClassName("btn");
		reset.getElement().setId("level-reset");
		bone.getElement().addClassName("btn");
		bone.getElement().setId("level-bone");
		abdomen.getElement().addClassName("btn");
		abdomen.getElement().setId("level-abdomen");
		brain.getElement().addClassName("btn");
		brain.getElement().setId("level-brain");
		pulmonary.getElement().addClassName("btn");
		pulmonary.getElement().setId("level-pulmonary");
		endoscopy.getElement().addClassName("btn");
		endoscopy.getElement().setId("level-endoscopy");
		
		// set up the slider and counter
		//slide.getElement().setPropertyString("type", "range");
		//count.getElement().setPropertyString("type", "number");

	}
	
	// toggle a toolbar button 
		private void toggleMode(Button btn, String mode ) {
			
			// deselect the other buttons
			level.removeStyleName("selected");
			move.removeStyleName("selected");
			zoom.removeStyleName("selected");
			animate.removeStyleName("selected");
			rotate.removeStyleName("selected");
			draw.removeStyleName("selected");
			tile.removeStyleName("selected");
			annotate.removeStyleName("selected");
			settings.removeStyleName("selected");
					
			// select the current button
			btn.addStyleName("selected");
			
			// this sets up the cursor, but it is not working at the moment
			//Element i = DOM.getElementById("image-viewer");
			//i.setClassName(mode);

			if (btn.equals(level) ) {
				
				// level mode
				tool = Tool.gradientTool;
				openMoreLevel();	 
				
			} else if (btn.equals(move)) {
				
				// move mode
				tool = Tool.moveTool;
				closeDrawer();
				
			} else if (btn.equals(zoom)) {
				// zoom mode
				tool = Tool.zoomTool;
				closeDrawer();
				
			} else if (btn.equals(rotate)) {
				
				// rotate mode
				tool = Tool.rotateTool;
				closeDrawer();
				
			} else if (btn.equals(animate)) {
				// move mode
				tool = Tool.animateTool;
				closeDrawer();

			}  else if (btn.equals(draw)) {
				// open the secondary container for drawing
				openMoreDraw();
				
			} else if (btn.equals(tile)) {
				// open the secondary container for tiling
				openMoreTile();
				
			}  else if (btn.equals(settings)) {
				// open the secondary container for settings
				openMoreSettings();	 
				
			} 
		}

	
	// open the tiling drawer
	private void openMoreTile() {

		selectTileMode(one);
		openTileDrawer();
	}
	
	// open the leveling drawer
	private void openMoreLevel() {

		openLevelDrawer();
	}
	
	// open the settings drawer
	private void openMoreSettings() {

		if (ImageListActivity.getBrowser() ) {
			selectSettingsMode(browser);
		}
		else  {
			selectSettingsMode(table);
		}
		openSettingsDrawer();

	}
	
	// open the drawing drawer
	private void openMoreDraw() {

		selectDrawMode(line, ROIShape.LINE);
		openDrawingDrawer();
		
	}

	// module selectDrawMode sets up the secondary drawer for the tiling options
	private void selectDrawMode(Button btn, ROIShape shape) {
		// deselect the other drawing buttons
		line.removeStyleName("selected");
		rectangle.removeStyleName("selected");
		circle.removeStyleName("selected");
		poly.removeStyleName("selected");
		openPoly.removeStyleName("selected");
		//text.removeStyleName("selected");
		arrow.removeStyleName("selected");
		oval.removeStyleName("selected");

				
		// select the current button
		btn.addStyleName("selected");
		tool = Tool.drawTool; 
		drawShape = shape;
		drawMode = false;


	}
	
	// module selectDrawMode sets up the secondary drawer for the tiling options
		private void toggleDrawMode(Button btn, ROIShape shape) {
			
			// if this button is already selected, then turn it off
			String style = btn.getStyleName();
			if (style.contains("selected")) {
				
				btn.removeStyleName("selected");
				tool = null; 
				drawShape = null;
				
			} else {
				
				// deselect the other drawing buttons
				line.removeStyleName("selected");
				rectangle.removeStyleName("selected");
				circle.removeStyleName("selected");
				oval.removeStyleName("selected");
				poly.removeStyleName("selected");
				openPoly.removeStyleName("selected");
				//text.removeStyleName("selected");
				arrow.removeStyleName("selected");
					
				// select this button
				btn.addStyleName("selected");
				tool = Tool.drawTool; 
				drawShape = shape;
			}
			drawMode = false;
		}
	
	// module openTileDrawer sets up the secondary drawer for the tiling options
	public native void openTileDrawer()/*-{
		
		$wnd.jQuery('#draw-options').hide();
		$wnd.jQuery('#level-options').hide();
		$wnd.jQuery('#settings-options').hide();
		$wnd.jQuery('#tile-options').attr('style', 'margin-left:2000px').show();
		var open = $wnd.jQuery("#tool-more").attr('height');
		
		if (!open) {
			$wnd.jQuery('#tool-more').slideDown( '8000', function() {
  				$wnd.jQuery('#tile-options').animate({'margin-left': '0'}, '8000');
  			});	
		} else {
			$wnd.jQuery('#tile-options').animate({'margin-left': '0'}, '8000');
		}
    				
  					 
	}-*/;
	
	// module openDrawingDrawer sets up the secondary drawer for the drawing options
	public native void openDrawingDrawer()/*-{
		
		$wnd.jQuery('#tile-options').hide();
		$wnd.jQuery('#settings-options').hide();
		$wnd.jQuery('#level-options').hide();
		$wnd.jQuery('#draw-options').attr('style', 'margin-left:2000px').show();
		var open = $wnd.jQuery("#tool-more").attr('height');
		
		if (!open) {
			$wnd.jQuery('#tool-more').slideDown( '8000', function() {
  				$wnd.jQuery('#draw-options').animate({'margin-left': '0'}, '8000');
  			});	
		} else {
			$wnd.jQuery('#draw-options').animate({'margin-left': '0'}, '8000');
		}					
  		
	}-*/;
	
	// module openSettingsDrawer sets up the secondary drawer for the Settings options
	public native void openSettingsDrawer()/*-{
	
		$wnd.jQuery('#draw-options').hide();
		$wnd.jQuery('#tile-options').hide();
		$wnd.jQuery('#level-options').hide();
		$wnd.jQuery('#settings-options').attr('style', 'margin-left:2000px').show();
		var open = $wnd.jQuery("#tool-more").attr('height');
	
		if (!open) {
			$wnd.jQuery('#tool-more').slideDown( '8000', function() {
					$wnd.jQuery('#settings-options').animate({'margin-left': '0'}, '8000');
				});	
		} else {
			$wnd.jQuery('#settings-options').animate({'margin-left': '0'}, '8000');
		}
				
					 
	}-*/;
	
	// module openLevelDrawer sets up the secondary drawer for the Leveling options
		public native void openLevelDrawer()/*-{
		
			$wnd.jQuery('#draw-options').hide();
			$wnd.jQuery('#tile-options').hide();
			$wnd.jQuery('#settings-options').hide();
			$wnd.jQuery('#level-options').attr('style', 'margin-left:2000px').show();
			var open = $wnd.jQuery("#tool-more").attr('height');
		
			if (!open) {
				$wnd.jQuery('#tool-more').slideDown( '8000', function() {
						$wnd.jQuery('#level-options').animate({'margin-left': '0'}, '8000');
					});	
			} else {
				$wnd.jQuery('#level-options').animate({'margin-left': '0'}, '8000');
			}
					
						 
		}-*/;
	
	// module closeDrawer closes the secondary drawer for buttons
	public native void closeDrawer()/*-{
	
		$wnd.jQuery('#tool-more').slideUp( '8000', function() {});					
		
	}-*/;
	
	 // module selectTileMode manages the tile container and current choice
	 private void selectTileMode(Button btn) {
		// deselect the other tiling buttons
		one.removeStyleName("selected");
		two.removeStyleName("selected");
		four.removeStyleName("selected");
		

		// select the current button
		btn.addStyleName("selected");

	}
	
	 // module selectSettingsMode sets the selected Settings button
	private void selectSettingsMode(Button btn) {
		// deselect the other settings buttons
		table.removeStyleName("selected");
		browser.removeStyleName("selected");
		

		// select the current button
		btn.addStyleName("selected");
		
		// disable or enable table, thumbs and browser
		if (btn == browser) {
			
			// show the browser needs and hide the table divs
			Element table = DOM.getElementById("cellTable");
			table.addClassName("hidden"); 
			Element thumbs = DOM.getElementById("imageTreeBlock");
			thumbs.addClassName("hidden");
			ImageListActivity.setBrowser(true); 
		
		} else if (btn == table) {
			
			// show the divs that the table  needs and hide the browser  
			Element table = DOM.getElementById("cellTable");
			table.removeClassName("hidden");
			Element thumbs = DOM.getElementById("imageTreeBlock");
			thumbs.removeClassName("hidden");
			ImageListActivity.setBrowser(false); 

		}

	}
	
	@UiHandler("imageSlider")
	void onChangeSlider(ValueChangeEvent<Integer> e) {
		// set up to the selected image
		Integer value = imageSlider.getValue();
		setIndexImage(value - 1);  // slider starts at 1, index at 0
		drawing.selectSet(getIndexImage());
		drawImage();
		drawSliderArrow();
	}
	
	
	// set up the image slider
	private void initImageSlider(int max) {
		
		if (max > 0) {
			imageSlider.update(1, max, 1, 1);
		} 		
	}
		
	// update the slider for the new selected image
	private void updateSlider() {
		
		int value = getIndexImage() + 1;
		console("updateSlider " + value);
		imageSlider.setValue(value);
	}

	
	// init the drawing handlers, move, down, up, and keypress
	void initDrawingHandlers() {
		
		drawing.addMouseMoveHandler(new MouseMoveHandler() {

			public void onMouseMove(MouseMoveEvent event) {
		
				mouseX = event.getRelativeX(drawing.getElement());
				mouseY = event.getRelativeY(drawing.getElement());
			
				imageX.setText(Integer.toString(mouseX));
				imageY.setText(Integer.toString(mouseY));
				
				switch (tool) {
				// change the coordinates numbers and change the brightness of
				// image
				case gradientTool:
					if (imageLoad) {
						try {
							handleImageMouseMove(Integer.toString(mouseX),
									Integer.toString(mouseY));
							imageWC.setText(Integer.toString(wcImage()));
							imageWW.setText(Integer.toString(wwImage()));
						} catch (Exception e) {
							GWT.log("JSNI methodo handleImage() threw a exception: ",
									e);
							e.printStackTrace();
						}
					}
					break;
				// update any ghosting graphic
				case drawTool: if  (click == true)  {

					drawing.updateShape(atualX, atualY, mouseX, mouseY);
					//drawImage();

					}
				}
			}
		});
		
		drawing.addMouseDownHandler(new MouseDownHandler() {// 1
	
			public void onMouseDown(MouseDownEvent event) {
				atualX = mouseX;
				atualY = mouseY;
				switch (tool) {
				case gradientTool:
					if (imageLoad) {
						handleImageMouseDown(Integer.toString(mouseX),
								Integer.toString(mouseY));
					}
					break;
				case moveTool: break;
				case zoomTool:break;
				case animateTool: break;
				case rotateTool: break;
				case drawTool:
					click = true;
					drawing.startShape(atualX, atualY, drawShape);
					break;	
				}
			}
		});
		
		drawing.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				console("onKeyPress");
				switch (tool) {
				case drawTool:
					if (click == true) {

						//String s = Character.toString(event.getCharCode());
						//drawComment(s,  atualX, atualY);
					}
					break;
				}
			}
		});
		
		drawing.addMouseUpHandler(new MouseUpHandler() {// 3
	
			public void onMouseUp(MouseUpEvent event) {
	
				switch (tool) {
				case gradientTool:
					if (imageLoad) {
						handleImageMouseUp();
					}
					break;
				case drawTool:
					if (click) {

						if (drawing.stopShape(atualX, atualY, mouseX, mouseY)) {
							click = false;
							if (drawing.validShape()) {
								drawing.saveShape();
								newROI();		 
							}
						}	
					}
					break;
					}
		
				}
		});
		
	
	

		// handle the scroll wheel in the drawing
		drawing.addMouseWheelHandler(new MouseWheelHandler() {
		
			public void onMouseWheel(MouseWheelEvent event) {
				//if (imageLoad) {
					if (event.getDeltaY() < 0) {
						upImages();
						if ((presenter.getImages().size() - 1) > getIndexImage())
							setIndexImage(getIndexImage() +1);
					} else {
						downImages();
						if (getIndexImage() > 0)
							setIndexImage(getIndexImage() -1);
					}

					drawSliderArrow();
					updateSlider();
					drawing.selectSet(getIndexImage());
					drawImage();
			
				//}
			}
		});
	}
		
		
	

	
}